#include <syslog.h>
#include <fcntl.h>
#include <sys/resource.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

// #include "apue.h"

void daemonize_test(const char * cmd)
{
  int i, fd0, fd1, fd2;
  pid_t pid;
  struct rlimit rl;
  struct sigaction sa;

  /* clear file creation mask. */
  umask(0);

  /* get  maximum number of file descriptors. */
  if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
    printf("%s: can't get file limit", cmd);

  /* become a session leader to lose controlling TTY. */
  if ((pid = fork()) < 0)//注释2
    printf("%s: can't fork", cmd);
  else if (pid != 0) /* parent */
    exit(0);
  setsid();//注释3

  /* * Ensure future opens won't allocate controlling TTYs. */
  sa.sa_handler = SIG_IGN;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = 0;
  if (sigaction(SIGHUP, &sa, NULL) < 0)
    printf("%s: can't ignore SIGHUP", cmd);
  if ((pid = fork()) < 0)//注释4
    printf("%s: can't fork", cmd);
  else if (pid != 0) /* parent */
    exit(0);

  /* * Change the current working directory to the root so * we won't prevent file systems from being unmounted. */
  if (chdir("/") < 0)//注释5
    printf("%s: can't change directory to /", cmd);

  /* * Close all open file descriptors. */
  if (rl.rlim_max == RLIM_INFINITY)
    rl.rlim_max = 1024;
  for (i = 0; i < rl.rlim_max; i++)
    close(i);//注释6

  /* * Attach file descriptors 0, 1, and 2 to /dev/null. */
  fd0 = open("/dev/null", O_RDWR);//注释7
  fd1 = dup(0);//注释7
  fd2 = dup(0);//注释7

  /* * Initialize the log file. */
  openlog(cmd, LOG_CONS, LOG_DAEMON);
  if (fd0 != 0 || fd1 != 1 || fd2 != 2) {
    syslog(LOG_ERR, "unexpected file descriptors %d %d %d",fd0, fd1, fd2);
    exit(1);
  }
}

int main()
{
  daemonize_test("ls");

  return 0;
}
